﻿/*
 * 20200923 oubl 把固定后缀改为变动的
 * */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace GKQC.Common
{
    public partial class FormStringSetting : Form
    {
        CommonString commonString = null;
        EncryptSugar yntacticSugar = EncryptSugar.GetInstance();
        //readonly string s0 = "123WER7890qwertyuiopasdfghjklzxcvbn123456789012er3";

        string s1 = "server={0};uid={1};pwd={2};database={3}";
        string s2 = "User Id={0}; Password = {1}; Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = {2})(PORT = {3})))(CONNECT_DATA = (SERVICE_NAME = {4})))";
        string s3 = "server={0};uid={1};pwd={2};database={3}";

        string con_sqlserver = "server={0};uid={1};pwd={2};database={3}";
        string con_oracle = "User Id={0}; Password = {1}; Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = {2})(PORT = {3})))(CONNECT_DATA = (SERVICE_NAME = {4})))";
        string con_mysql = "server={0};database={1};uid={2};pwd={3};charset=utf8";
        string con_postgressql = "PORT={0}; DATABASE={1};HOST={2};PASSWORD={3};USER ID = {4}";

        public FormStringSetting()
        {
            InitializeComponent();
            try
            {
                commonString = Settings.GetDataObjectFile<CommonString>("CommonString.Dat");
                if (commonString != null)
                {
                    this.textBox1.Text = commonString.S1;
                    this.textBox2.Text = commonString.S2;
                    this.textBox3.Text = commonString.S3;
                    this.textBox4.Text = commonString.S4;
                    this.textBox5.Text = commonString.S5;

                    this.textBox11.Text = commonString.S11;
                    this.textBox12.Text = commonString.S12;
                    this.textBox13.Text = commonString.S13;
                    this.textBox14.Text = commonString.S14;
                    this.textBox15.Text = commonString.S15;

                    this.textBox21.Text = commonString.S21;
                    this.textBox22.Text = commonString.S22;
                    this.textBox23.Text = commonString.S23;
                    this.textBox24.Text = commonString.S24;
                    this.textBox25.Text = commonString.S25;

                    this.cboDbType.SelectedIndex = commonString.DbType;
                    this.cboErpDbType.SelectedIndex = commonString.ErpDbType;
                }
                else commonString = new CommonString();
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                MessageBox.Show(ex.Message);
            }

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            this.Validate();

            commonString.S1 = this.textBox1.Text;
            commonString.S2 = this.textBox2.Text;
            commonString.S3 = this.textBox3.Text;
            commonString.S4 = this.textBox4.Text;
            commonString.DbType = cboDbType.SelectedIndex;
            commonString.ErpDbType = cboErpDbType.SelectedIndex;
            if (this.textBox5.Text.Length < 50)
            {
                commonString.S5 = yntacticSugar.Encrypto(this.textBox5.Text) + RandomSugar.GetRandWord(50); //+s0;
            }

            commonString.S11 = this.textBox11.Text;
            commonString.S12 = this.textBox12.Text;
            commonString.S13 = this.textBox13.Text;
            commonString.S14 = this.textBox14.Text;
            if (this.textBox15.Text.Length < 50)
            {
                commonString.S15 = yntacticSugar.Encrypto(this.textBox15.Text) + RandomSugar.GetRandWord(50); //s0;
            }

            commonString.S21 = this.textBox21.Text;
            commonString.S22 = this.textBox22.Text;
            commonString.S23 = this.textBox23.Text;
            commonString.S24 = this.textBox24.Text;
            if (this.textBox25.Text.Length < 50)
            {
                commonString.S25 = yntacticSugar.Encrypto(this.textBox25.Text) + RandomSugar.GetRandWord(50);// s0;
            }

            if (commonString.DbType < 0) commonString.DbType = 0;
            if (commonString.ErpDbType < 0) commonString.ErpDbType = 0;

            Settings.SaveObject(commonString,"CommonString.Dat");

            MessageBox.Show("保存成功！","提示");
        }

        //品质系统数据库测试
        private void btn1_Click(object sender, EventArgs e)
        {
            //var es = EncryptSugar.GetInstance();
            //string s = string.Format(s1, this.textBox1.Text + (string.IsNullOrWhiteSpace(this.textBox3.Text) ? string.Empty : ("," + this.textBox3.Text))
            //    , this.textBox4.Text
            //    , (this.textBox5.Text.Length > 50 ? es.Decrypto(this.textBox5.Text.Substring(0, this.textBox5.Text.Length - 50)) : this.textBox5.Text)
            //    , this.textBox2.Text);
            //TestContext t = new TestContext(s, SqlSugar.DbType.SqlServer);

            TestContext t = GetQcContext();
            try
            {
                if (t.Test())
                {
                    MessageBox.Show("數據庫連接成功", "測試成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("數據庫連接失敗", "測試失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "測試異常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btn21_Click(object sender, EventArgs e)
        {

            var es = EncryptSugar.GetInstance();
            string s = string.Format(s3, this.textBox21.Text + (string.IsNullOrWhiteSpace(this.textBox23.Text) ? string.Empty : ("," + this.textBox23.Text))
                , this.textBox24.Text
                , (this.textBox25.Text.Length > 50 ? es.Decrypto(this.textBox25.Text.Substring(0, this.textBox25.Text.Length - 50)) : this.textBox25.Text)
                , this.textBox22.Text);
            TestContext t = new TestContext(s, SqlSugar.DbType.SqlServer);
            try
            {
                if (t.Test())
                {
                    MessageBox.Show("數據庫連接成功", "測試成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("數據庫連接失敗", "測試失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "測試異常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        //ERP数据库测试
        private void btn11_Click(object sender, EventArgs e)
        {
            var es = EncryptSugar.GetInstance();
            string s = string.Format(s2,
                this.textBox14.Text
                , (this.textBox15.Text.Length > 50 ? es.Decrypto(this.textBox15.Text.Substring(0, this.textBox15.Text.Length - 50)) : this.textBox15.Text)
                ,this.textBox11.Text
                , string.IsNullOrWhiteSpace(this.textBox13.Text) ? "1521" : this.textBox13.Text
                , this.textBox12.Text);
            TestContext t = new TestContext(s, SqlSugar.DbType.Oracle);
            try
            {
                if (t.Test())
                {
                    MessageBox.Show("數據庫連接成功", "測試成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("數據庫連接失敗", "測試失敗", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "測試異常", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnBackup_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog sf = new SaveFileDialog();
                DialogResult dr = sf.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    string path = sf.FileName;
                    string sql = " BACKUP DATABASE " + textBox2.Text + " to DISK = '" + path + "'";
                    TestContext t = GetQcContext();
                    object o = null;
                    t.db.Ado.ExecuteCommand(sql, o);

                    //SqlConnection con = new SqlConnection(connectionString);
                    //con.Open();
                    //SqlCommand cmd = new SqlCommand(sql, con);
                    //cmd.ExecuteNonQuery();
                    MessageBox.Show("数据库备份成功,备份文件名称："+ path);
                    //con.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            DialogResult dr = ofd.ShowDialog();
            if (dr == DialogResult.OK)
            {
                try
                {
                    var es = EncryptSugar.GetInstance();
                    string s = string.Format(s1, this.textBox1.Text + (string.IsNullOrWhiteSpace(this.textBox3.Text) ? string.Empty : ("," + this.textBox3.Text))
                        , this.textBox4.Text
                        , (this.textBox5.Text.Length > 50 ? es.Decrypto(this.textBox5.Text.Substring(0, this.textBox5.Text.Length - 50)) : this.textBox5.Text)
                        , "master" //this.textBox2.Text
                        );
                    TestContext t = new TestContext(s, SqlSugar.DbType.SqlServer);

                    string connectionString = "server={0};database={1};uid={2};pwd={3}";
                    connectionString = string.Format(connectionString
                        , textBox1.Text
                        , "master"
                        , textBox4.Text
                        , (this.textBox5.Text.Length > 50 ? es.Decrypto(this.textBox5.Text.Substring(0, this.textBox5.Text.Length - 50)) : this.textBox5.Text
                        ));
                    
                    SqlConnection con = new SqlConnection(connectionString);
                    con.Open();

                    string sql2 = "if exists(select * from sys.databases where name = '" + textBox2.Text + "') select 1 else select 0";
                    SqlCommand cmd = new SqlCommand(sql2, con);
                    if (Convert.ToBoolean(cmd.ExecuteScalar()))
                    {
                        MessageBox.Show("数据库名称已存在，不能还原！");
                        return;
                    }

                    string dbName = textBox2.Text;
                    string cmdText = @"restore database " + dbName + " from disk='" + ofd.FileName + "' "
                    + " with move 'typee'     to '" + Environment.CurrentDirectory +  "\\" + dbName + ".mdf'"
                    + ",move 'typee_log' to '" + Environment.CurrentDirectory + "\\" + dbName + ".ldf'";
                    string sql = cmdText;
                    cmd = new SqlCommand(sql, con);
                    cmd.ExecuteNonQuery();
                    con.Close();

                    MessageBox.Show("数据库还原成功，数据库名称为：" + dbName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        TestContext GetQcContext()
        {
            var es = EncryptSugar.GetInstance();
            string s = string.Format(s1, this.textBox1.Text + (string.IsNullOrWhiteSpace(this.textBox3.Text) ? string.Empty : ("," + this.textBox3.Text))
                , this.textBox4.Text
                , (this.textBox5.Text.Length > 50 ? es.Decrypto(this.textBox5.Text.Substring(0, this.textBox5.Text.Length - 50)) : this.textBox5.Text)
                , this.textBox2.Text);
            TestContext t = new TestContext(s, SqlSugar.DbType.SqlServer);
            //Logger.LogMessage(s);
            return t;
        }

        private void FormStringSetting_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == (Keys.Control | Keys.Alt) && e.KeyCode == Keys.F5)
            {
                btnBackup.Visible = !btnBackup.Visible;
                btnRestore.Visible = !btnRestore.Visible;
            }
        }
    }

    [Serializable]
    public class CommonString
    {
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }

        public string S11 { get; set; }
        public string S12 { get; set; }
        public string S13 { get; set; }
        public string S14 { get; set; }
        public string S15 { get; set; }

        public string S21 { get; set; }
        public string S22 { get; set; }
        public string S23 { get; set; }
        public string S24 { get; set; }
        public string S25 { get; set; }

        public int DbType { get; set; }
        public int ErpDbType { get; set; }
    }
}
